import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import { clearAllCookies } from '@/utils/cookieUtil'
import i18n from '../i18n'

let axiosService = axios.create({
  // 发布生产时，此处需要解除注释
  // baseURL: 'https://www.gaiacash.net',
  // baseURL: 'http://101.37.164.15',
  // baseURL: 'http://www.gaiacash.net',
  timeout: 30000
  // withCredentials: true,
  // headers: {
  //
  // },
})

axiosService.interceptors.request.use((config) => {
  if (config.data) {
    Object.assign(config.data, {
      lang: window.lang
    })
  } else {
    config.data = {
      lang: window.lang
    }
  }
  if (config.method === 'get') {
    config.params = config.data
  }

  config.data = qs.stringify(config.data)

  const newConfig = Object.assign({
    responseType: 'json'
  }, config)
  return newConfig
}, (error) => {
  ElMessage.error(i18n.global.t('requestError'))
  return Promise.reject(error)
})

axiosService.interceptors.response.use((response) => {
  const data = response.data
  if (+data.status === 0) {
    return data.data
  } else if (+data.status === 9999) {
    ElMessage.error(i18n.global.t('noPermission'))
    // window.location = '/noPermission'
  } else if (+data.status === 9998) {
    clearAllCookies()
    localStorage.setItem('userName', '')
    localStorage.setItem('userId', '')
    window.location = '/login'
  } else {
    ElMessage.error(data.msg)
    return Promise.reject(data)
  }
}, (error) => {
  ElMessage.error(i18n.global.t('requestError'))
  return Promise.reject(error)
})
export default axiosService
